package com.soup.lab.el;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.util.List;

public class SpringELTestCase {
    SpelExpressionParser parser = new SpelExpressionParser();
    @Test
    public void test() {
        Expression expression = parser.parseExpression("1+2");
        Integer value = expression.getValue(Integer.class);
        Assertions.assertEquals(3, value);
    }

    @Test
    public void testJavaBean() {
        Expression exp1 = parser.parseExpression("'abc'.bytes.length");
        Integer len = exp1.getValue(Integer.class);
        Assertions.assertEquals(3, len);
    }

    @Test
    public void testRootObject() {
        Expression exp = parser.parseExpression("id + ':' + val");
        String abc = exp.getValue(new Root(1, "abc"), String.class);
        Assertions.assertEquals("1:abc", abc);
    }

    @Test
    public void testMethod() {
        Expression exp = parser.parseExpression("isVIP()");
        Boolean value = exp.getValue(new Root(1, "abc"), Boolean.class);
        Assertions.assertEquals(false, value);
    }
    @Test
    public void inlineList() {
        List numbers = (List) parser.parseExpression("{1,2,3,4}").getValue();
        System.out.println(numbers);
    }
    @Test
    public void collection() {
        List numbers = parser.parseExpression("{1,2,3,4}.?[#this > 2].![#this * 2]").getValue(List.class);
        // [6, 8]
        System.out.println(numbers);
    }

    @Test
    public void safe() {
        String nullsafe = parser.parseExpression("null?.toString()").getValue(String.class);
        System.out.println(nullsafe);
    }

    public static class Root {
        private final String val;

        private final Integer id;

        public Root(Integer id, String val) {
            this.val = val;
            this.id = id;
        }

        public String getVal() {
            return val;
        }

        public Integer getId() {
            return id;
        }

        public boolean isVIP() {
            return id > 1;
        }

    }


}
